package com.niyue.sandbox.uclock.core;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;

public class AbstractTimer implements Timer {
	private static Logger logger=Logger.getLogger(AbstractTimer.class);
	private List<Clock> clocks=new ArrayList<Clock>();
	private List<EventFactory> eventFactories=new ArrayList<EventFactory>();
	public void register(Clock clock) {
		if (logger.isDebugEnabled()) {
			logger.debug(clock.getName()+" is registered with the timer.");
		}
		clocks.add(clock);
	}

	public void remove(Clock clock) {
		if (logger.isDebugEnabled()) {
			logger.debug(clock.getName()+" is removed from the updated list.");
		}
		clocks.remove(clock);
	}
	public void regiesterFactory(EventFactory factory){
		eventFactories.add(factory);
	}
	public void removeFacotry(EventFactory factory){
		eventFactories.remove(factory);
	}

	public void notifyClock() {
		for (Iterator iter = eventFactories.iterator(); iter.hasNext();) {
			EventFactory eventFactory = (EventFactory) iter.next();
			List<Event> events=eventFactory.getEvents(new DateTime());
			for (Iterator iterator = events.iterator(); iterator.hasNext();) {
				Event event = (Event) iterator.next();
				for (Iterator clockIter = clocks.iterator(); clockIter.hasNext();) {
					Clock clock = (Clock) clockIter.next();
					clock.update(event);
				}
			}
		}
	}
}
